<template>
  <app-dialog-form
    title="添加虚拟评价"
    :confirm="handleSubmit"
    width="800px"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      size="small"
      v-loading="formLoading"
    >
      <el-form-item
        label="商品"
        prop="rule_name"
      >
        <app-image-upload-input
          v-if="formData.image.image!==''"
          v-model="formData.image.image"
          title="选择评价商品"
        />
        <el-row
          v-else
          class="upload"
          align="middle"
          justify="center"
          @click="selectFormVisible = true"
        >
          <i
            class="el-icon-attract"
            style="font-size: 26px;"
          />
        </el-row>
      </el-form-item>

      <el-form-item
        label="用户头像"
        prop="account"
      >
        <app-image-upload-input
          v-model="formData.avatar"
          title="上传用户头像"
        />
      </el-form-item>
      <el-form-item
        label="用户名称"
        prop="account"
      >
        <el-input
          size="small"
          v-model="formData.nickname"
          placeholder="请输入用户名称"
        />
      </el-form-item>
      <el-form-item
        label="评价文字"
        prop="comment"
      >
        <el-input
          size="small"
          type="textarea"
          :rows="4"
          v-model="formData.comment"
          placeholder="请输入评论内容"
        />
      </el-form-item>
      <el-form-item
        label="商品分数"
        prop="score"
      >
        <el-rate
          size="small"
          v-model="formData.product_score"
          show-score
          text-color="#ff9900"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
        />
      </el-form-item>
      <el-form-item
        label="服务分数"
        prop="score"
      >
        <el-rate
          size="small"
          v-model="formData.service_score"
          show-score
          text-color="#ff9900"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
        />
      </el-form-item>

      <el-form-item
        label="评价图片"
        prop="score"
      >
        <app-image-upload-input
          v-model="formData.pics"
          :options="{maxSelect: 5}"
          title="上传评价图片"
        />
      </el-form-item>

      <el-form-item
        label="评论时间"
        prop="score"
      >
        <el-date-picker
          v-model="formData.add_time"
          type="datetime"
          placeholder="选择日期时间"
          size="small"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width:210px;"
        />
      </el-form-item>
    </el-form>
    <app-product-select
      :model-value="selectFormVisible"
      :selected="setImageField"
      @cancel="selectFormVisible = false"
    />
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import type { FictitiousReply, Product, RuleSpec } from '@/api/types/product'
import { getFictitiousReplyFormOptions, saveFictitiousReply } from '@/api/product'
// import ProductSelectForm from './ProductSelectForm.vue'

interface EmitsType {
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formLoading = ref(false)
const selectFormVisible = ref(false)
const formData = ref<FictitiousReply>({
  image: {
    image: '',
    product_id: 0
  },
  avatar: '',
  nickname: '',
  comment: '',
  product_score: 0,
  service_score: 0,
  pics: [],
  add_time: undefined
})

const formRules = ref<IFormRule>({})

formLoading.value = true
const handleDialogOpen = () => {
  formLoading.value = true
  loadFictitiousReplyFormOptions().finally(() => {
    formLoading.value = false
  })
}
const defaultTmpSpec = {
  value: '',
  detail: ['']
}

const setImageField = async (product: Product|null) => {
  if (product) {
    formData.value.image = { image: product.image, product_id: product.id }
  }
  selectFormVisible.value = false
}
const tmpSpec = ref<RuleSpec>(JSON.parse(JSON.stringify(defaultTmpSpec)))

const isTmpSpecShow = ref(false)

const resetTmpSpec = () => {
  isTmpSpecShow.value = false
  tmpSpec.value = JSON.parse(JSON.stringify(defaultTmpSpec))
}

const loadFictitiousReplyFormOptions = async () => {
  const rules = await getFictitiousReplyFormOptions()
  // 没什么卵用
  rules.forEach(item => {
    formRules.value[item.field] = [{ required: true, message: item.props?.placeholder || item.props?.title || `请选择${item.title}`, trigger: 'blur' }]
  })
}

const handleDialogClosed = () => {
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
  resetFormData()
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  await saveFictitiousReply(formData.value)
  // reset formData
  resetFormData()
  resetTmpSpec()
  emit('success')
  ElMessage.success('保存成功')
}

const resetFormData = () => {
  formData.value = {
    image: {
      image: '',
      product_id: 0
    },
    avatar: '',
    nickname: '',
    comment: '',
    product_score: 0,
    service_score: 0,
    pics: [],
    add_time: undefined
  }
}
</script>

<style lang="scss" scoped>
.el-dialog {
  margin-left: 80px;
}
.upload {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0,0,0,.1);
  border-radius: 4px;
  background: rgba(0,0,0,.02);
  cursor: pointer;
  flex: 1;
  margin-right: 8px;
  position: relative;
}
</style>
